package cn.iocoder.yudao.module.erp.service.purchase;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceStatusEnum;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductVO;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.applyOrder.ErpPurchaseApplyOrderSaveReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.order.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpPurchaseApplyOrderDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpPurchaseApplyOrderItemDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpPurchaseOrderDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpSupplierDO;
import cn.iocoder.yudao.module.erp.dal.mysql.product.ErpProductMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.purchase.ErpPurchaseApplyOrderItemMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.purchase.ErpPurchaseApplyOrderMapper;
import cn.iocoder.yudao.module.erp.dal.redis.no.ErpNoRedisDAO;
import cn.iocoder.yudao.module.erp.enums.ErpAuditStatus;
import cn.iocoder.yudao.module.erp.enums.ErpPurchaseOrderStatus;
import cn.iocoder.yudao.module.erp.enums.ErpPurchaseOrderTypeStatus;
import cn.iocoder.yudao.module.erp.service.finance.ErpAccountService;
import cn.iocoder.yudao.module.erp.service.product.ErpProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.ConstraintViolationException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;

// TODO 芋艿：记录操作日志

/**
 * ERP 采购订单 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ErpPurchaseApplyOrderServiceImpl implements ErpPurchaseApplyOrderService {

    @Resource
    private ErpPurchaseApplyOrderMapper purchaseOrderMapper;
    @Resource
    private ErpPurchaseApplyOrderItemMapper purchaseOrderItemMapper;

    @Resource
    private ErpNoRedisDAO noRedisDAO;

    @Resource
    private ErpProductService productService;
    @Resource
    private ErpSupplierService supplierService;
    @Resource
    private ErpAccountService accountService;
    @Resource
    private ErpProductMapper erpProductMapper;

    @Value("${task.purchase_applyOrder.key:purchase_applyOrder_audit}")
    private String purchaseApplyOrderTask;
    @Resource
    private BpmProcessInstanceApi processInstanceApi;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createPurchaseOrder(ErpPurchaseApplyOrderSaveReqVO createReqVO) {
        // 1.1 校验订单项的有效性
        List<ErpPurchaseApplyOrderItemDO> purchaseOrderItems = validatePurchaseOrderItems(createReqVO.getItems());
        // 1.2 校验供应商
        ErpSupplierDO supplierDO = supplierService.validateSupplier(createReqVO.getSupplierId());
        // 1.3 校验结算账户
//        if (createReqVO.getAccountId() != null) {
//            accountService.validateAccount(createReqVO.getAccountId());
//        }
        // 1.4 生成订单号，并校验唯一性
        String no = noRedisDAO.generate(ErpNoRedisDAO.PURCHASE_APPLY_ORDER_NO_PREFIX);
        if (purchaseOrderMapper.selectByNo(no) != null) {
            throw exception(PURCHASE_ORDER_NO_EXISTS);
        }

        // 2.1 插入订单
        ErpPurchaseApplyOrderDO purchaseOrder = BeanUtils.toBean(createReqVO, ErpPurchaseApplyOrderDO.class, in -> in
                .setNo(no).setStatus(BpmProcessInstanceStatusEnum.RUNNING.getStatus()));
        calculateTotalPrice(purchaseOrder, purchaseOrderItems);
        purchaseOrderMapper.insert(purchaseOrder);
        // 2.2 插入订单项
        purchaseOrderItems.forEach(o -> o.setOrderId(purchaseOrder.getId()));
        purchaseOrderItemMapper.insertBatch(purchaseOrderItems);

        //插入工作流
        Map<String, Object> processInstanceVariables = new HashMap<>();
        processInstanceVariables.put("purchaseApplyOrderId", purchaseOrder.getId());
        processInstanceVariables.put("purchaseApplyOrderNo", purchaseOrder.getNo());
        processInstanceVariables.put("purchaseApplyOrderTime", purchaseOrder.getOrderTime());
        processInstanceVariables.put("purchaseApplySupplierName", supplierDO.getName());
        processInstanceVariables.put("totalPrice", purchaseOrder.getTotalPrice());
        String processInstanceId = processInstanceApi.createProcessInstance(getLoginUserId(),
                new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(purchaseApplyOrderTask)
                        .setVariables(processInstanceVariables).setBusinessKey(String.valueOf(purchaseOrder.getId()))
        );
        ErpPurchaseApplyOrderDO update = new ErpPurchaseApplyOrderDO();
        update.setId(purchaseOrder.getId());
        update.setProcessInstanceId(processInstanceId);
        purchaseOrderMapper.updateById(update);

        return purchaseOrder.getId();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createPurchaseOrder2(ErpPurchaseApplyOrderSaveReqVO createReqVO) {
        // 1.1 校验订单项的有效性
        List<ErpPurchaseApplyOrderItemDO> purchaseOrderItems = validatePurchaseOrderItems(createReqVO.getItems());
        // 1.2 校验供应商
//        ErpSupplierDO supplierDO = supplierService.validateSupplier(createReqVO.getSupplierId());
        // 1.3 校验结算账户
//        if (createReqVO.getAccountId() != null) {
//            accountService.validateAccount(createReqVO.getAccountId());
//        }
        // 1.4 生成订单号，并校验唯一性
        String no = noRedisDAO.generate(ErpNoRedisDAO.PURCHASE_APPLY_ORDER_NO_PREFIX);
        if (purchaseOrderMapper.selectByNo(no) != null) {
            throw exception(PURCHASE_ORDER_NO_EXISTS);
        }

        // 2.1 插入订单
        ErpPurchaseApplyOrderDO purchaseOrder = BeanUtils.toBean(createReqVO, ErpPurchaseApplyOrderDO.class, in -> in
                .setNo(no).setStatus(BpmProcessInstanceStatusEnum.RUNNING.getStatus()));
        purchaseOrder.setOrderType(ErpPurchaseOrderTypeStatus.ONE.getStatus());
        calculateTotalPrice(purchaseOrder, purchaseOrderItems);
        purchaseOrderMapper.insert(purchaseOrder);
        // 2.2 插入订单项
        purchaseOrderItems.forEach(o -> o.setOrderId(purchaseOrder.getId()));
        purchaseOrderItemMapper.insertBatch(purchaseOrderItems);


        return purchaseOrder.getId();
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePurchaseOrder2(ErpPurchaseApplyOrderSaveReqVO updateReqVO) {
        // 1.1 校验存在
        ErpPurchaseApplyOrderDO purchaseOrder = validatePurchaseOrderExists(updateReqVO.getId());
        if (ErpAuditStatus.APPROVE.getStatus().equals(purchaseOrder.getStatus())) {
            throw exception(PURCHASE_ORDER_UPDATE_FAIL_APPROVE, purchaseOrder.getNo());
        }
        // 1.2 校验供应商
//        ErpSupplierDO supplierDO = supplierService.validateSupplier(updateReqVO.getSupplierId());
        // 1.3 校验结算账户
//        if (updateReqVO.getAccountId() != null) {
//            accountService.validateAccount(updateReqVO.getAccountId());
//        }
        // 1.4 校验订单项的有效性
        List<ErpPurchaseApplyOrderItemDO> purchaseOrderItems = validatePurchaseOrderItems(updateReqVO.getItems());

        // 2.1 更新订单
        ErpPurchaseApplyOrderDO updateObj = BeanUtils.toBean(updateReqVO, ErpPurchaseApplyOrderDO.class);
        calculateTotalPrice(updateObj, purchaseOrderItems);
        purchaseOrderMapper.updateById(updateObj);
        // 2.2 更新订单项
        updatePurchaseOrderItemList(updateReqVO.getId(), purchaseOrderItems);

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePurchaseOrder(ErpPurchaseApplyOrderSaveReqVO updateReqVO) {
        // 1.1 校验存在
        ErpPurchaseApplyOrderDO purchaseOrder = validatePurchaseOrderExists(updateReqVO.getId());
        if (ErpAuditStatus.APPROVE.getStatus().equals(purchaseOrder.getStatus())) {
            throw exception(PURCHASE_ORDER_UPDATE_FAIL_APPROVE, purchaseOrder.getNo());
        }
        // 1.2 校验供应商
        ErpSupplierDO supplierDO = supplierService.validateSupplier(updateReqVO.getSupplierId());
        // 1.3 校验结算账户
//        if (updateReqVO.getAccountId() != null) {
//            accountService.validateAccount(updateReqVO.getAccountId());
//        }
        // 1.4 校验订单项的有效性
        List<ErpPurchaseApplyOrderItemDO> purchaseOrderItems = validatePurchaseOrderItems(updateReqVO.getItems());

        // 2.1 更新订单
        ErpPurchaseApplyOrderDO updateObj = BeanUtils.toBean(updateReqVO, ErpPurchaseApplyOrderDO.class);
        calculateTotalPrice(updateObj, purchaseOrderItems);
        purchaseOrderMapper.updateById(updateObj);
        // 2.2 更新订单项
        updatePurchaseOrderItemList(updateReqVO.getId(), purchaseOrderItems);

        //插入工作流
        Map<String, Object> processInstanceVariables = new HashMap<>();
        processInstanceVariables.put("purchaseApplyOrderId", purchaseOrder.getId());
        processInstanceVariables.put("purchaseApplyOrderNo", purchaseOrder.getNo());
        processInstanceVariables.put("purchaseApplyOrderTime", purchaseOrder.getOrderTime());
        processInstanceVariables.put("purchaseApplySupplierName", supplierDO.getName());
        processInstanceVariables.put("totalPrice", purchaseOrder.getTotalPrice());
        String processInstanceId = processInstanceApi.createProcessInstance(getLoginUserId(),
                new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(purchaseApplyOrderTask)
                        .setVariables(processInstanceVariables).setBusinessKey(String.valueOf(purchaseOrder.getId()))
        );
        ErpPurchaseApplyOrderDO update = new ErpPurchaseApplyOrderDO();
        update.setId(purchaseOrder.getId());
        update.setProcessInstanceId(processInstanceId);
        purchaseOrderMapper.updateById(update);


    }

    private void calculateTotalPrice(ErpPurchaseApplyOrderDO purchaseOrder, List<ErpPurchaseApplyOrderItemDO> purchaseOrderItems) {
        purchaseOrder.setTotalCount(getSumValue(purchaseOrderItems, ErpPurchaseApplyOrderItemDO::getCount, BigDecimal::add));
        purchaseOrder.setTotalProductPrice(getSumValue(purchaseOrderItems, ErpPurchaseApplyOrderItemDO::getTotalPrice, BigDecimal::add, BigDecimal.ZERO));
        purchaseOrder.setTotalTaxPrice(getSumValue(purchaseOrderItems, ErpPurchaseApplyOrderItemDO::getTaxPrice, BigDecimal::add, BigDecimal.ZERO));
        purchaseOrder.setTotalPrice(purchaseOrder.getTotalProductPrice().add(purchaseOrder.getTotalTaxPrice()));
        // 计算优惠价格
        if (purchaseOrder.getDiscountPercent() == null) {
            purchaseOrder.setDiscountPercent(BigDecimal.ZERO);
        }
        purchaseOrder.setDiscountPrice(MoneyUtils.priceMultiplyPercent(purchaseOrder.getTotalPrice(), purchaseOrder.getDiscountPercent()));
        purchaseOrder.setTotalPrice(purchaseOrder.getTotalPrice().subtract(purchaseOrder.getDiscountPrice()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePurchaseOrderStatus(Long id, Integer status) {
        boolean approve = ErpPurchaseOrderStatus.PASS.getStatus().equals(status);
        // 1.1 校验存在
        ErpPurchaseApplyOrderDO purchaseOrder = validatePurchaseOrderExists(id);
        // 1.2 校验状态
        if (purchaseOrder.getStatus().equals(status)) {
            throw exception(approve ? PURCHASE_ORDER_APPROVE_FAIL : PURCHASE_ORDER_PROCESS_FAIL);
        }
        // 1.3 存在采购入单，无法反审核
        if (!approve && purchaseOrder.getInCount().compareTo(BigDecimal.ZERO) > 0) {
            throw exception(PURCHASE_ORDER_PROCESS_FAIL_EXISTS_IN);
        }
        // 1.4 存在采购退货单，无法反审核
        if (!approve && purchaseOrder.getReturnCount().compareTo(BigDecimal.ZERO) > 0) {
            throw exception(PURCHASE_ORDER_PROCESS_FAIL_EXISTS_RETURN);
        }

        // 2. 更新状态
        int updateCount = purchaseOrderMapper.updateByIdAndStatus(id, purchaseOrder.getStatus(),
                new ErpPurchaseApplyOrderDO().setStatus(status));
        if (updateCount == 0) {
            throw exception(approve ? PURCHASE_ORDER_APPROVE_FAIL : PURCHASE_ORDER_PROCESS_FAIL);
        }
        if(approve){
            //目前这里处理，审核通过之后，需要吧这个数据，插入到基础出库表中

        }
    }

    private List<ErpPurchaseApplyOrderItemDO> validatePurchaseOrderItems(List<ErpPurchaseApplyOrderSaveReqVO.OrderItem> list) {
        // 1. 校验产品存在
        List<ErpProductDO> productList = productService.validProductList(
                convertSet(list, ErpPurchaseApplyOrderSaveReqVO.OrderItem::getProductId));
        Map<Long, ErpProductDO> productMap = convertMap(productList, ErpProductDO::getId);
        // 2. 转化为 ErpPurchaseApplyOrderItemDO 列表
        return convertList(list, o -> BeanUtils.toBean(o, ErpPurchaseApplyOrderItemDO.class, item -> {
            item.setProductUnitId(productMap.get(item.getProductId()).getUnitId());
            item.setTotalPrice(MoneyUtils.priceMultiply(item.getProductPrice(), item.getCount()));
            if (item.getTotalPrice() == null) {
                return;
            }
            if (item.getTaxPercent() != null) {
                item.setTaxPrice(MoneyUtils.priceMultiplyPercent(item.getTotalPrice(), item.getTaxPercent()));
            }
        }));
    }

    private void updatePurchaseOrderItemList(Long id, List<ErpPurchaseApplyOrderItemDO> newList) {
        // 第一步，对比新老数据，获得添加、修改、删除的列表
        List<ErpPurchaseApplyOrderItemDO> oldList = purchaseOrderItemMapper.selectListByOrderId(id);
        List<List<ErpPurchaseApplyOrderItemDO>> diffList = diffList(oldList, newList, // id 不同，就认为是不同的记录
                (oldVal, newVal) -> oldVal.getId().equals(newVal.getId()));

        // 第二步，批量添加、修改、删除
        if (CollUtil.isNotEmpty(diffList.get(0))) {
            diffList.get(0).forEach(o -> o.setOrderId(id));
            purchaseOrderItemMapper.insertBatch(diffList.get(0));
        }
        if (CollUtil.isNotEmpty(diffList.get(1))) {
            purchaseOrderItemMapper.updateBatch(diffList.get(1));
        }
        if (CollUtil.isNotEmpty(diffList.get(2))) {
            purchaseOrderItemMapper.deleteBatchIds(convertList(diffList.get(2), ErpPurchaseApplyOrderItemDO::getId));
        }
    }

    @Override
    public void updatePurchaseOrderInCount(Long id, Map<Long, BigDecimal> inCountMap) {
        List<ErpPurchaseApplyOrderItemDO> orderItems = purchaseOrderItemMapper.selectListByOrderId(id);
        // 1. 更新每个采购订单项
        orderItems.forEach(item -> {
            BigDecimal inCount = inCountMap.getOrDefault(item.getId(), BigDecimal.ZERO);
            if (item.getInCount().equals(inCount)) {
                return;
            }
            if (inCount.compareTo(item.getCount()) > 0) {
                throw exception(PURCHASE_ORDER_ITEM_IN_FAIL_PRODUCT_EXCEED,
                        productService.getProduct(item.getProductId()).getName(), item.getCount());
            }
            purchaseOrderItemMapper.updateById(new ErpPurchaseApplyOrderItemDO().setId(item.getId()).setInCount(inCount));
        });
        // 2. 更新采购订单
        BigDecimal totalInCount = getSumValue(inCountMap.values(), value -> value, BigDecimal::add, BigDecimal.ZERO);
        purchaseOrderMapper.updateById(new ErpPurchaseApplyOrderDO().setId(id).setInCount(totalInCount));
    }

    @Override
    public void updatePurchaseOrderReturnCount(Long orderId, Map<Long, BigDecimal> returnCountMap) {
        List<ErpPurchaseApplyOrderItemDO> orderItems = purchaseOrderItemMapper.selectListByOrderId(orderId);
        // 1. 更新每个采购订单项
        orderItems.forEach(item -> {
            BigDecimal returnCount = returnCountMap.getOrDefault(item.getId(), BigDecimal.ZERO);
            if (item.getReturnCount().equals(returnCount)) {
                return;
            }
            if (returnCount.compareTo(item.getInCount()) > 0) {
                throw exception(PURCHASE_ORDER_ITEM_RETURN_FAIL_IN_EXCEED,
                        productService.getProduct(item.getProductId()).getName(), item.getInCount());
            }
            purchaseOrderItemMapper.updateById(new ErpPurchaseApplyOrderItemDO().setId(item.getId()).setReturnCount(returnCount));
        });
        // 2. 更新采购订单
        BigDecimal totalReturnCount = getSumValue(returnCountMap.values(), value -> value, BigDecimal::add, BigDecimal.ZERO);
        purchaseOrderMapper.updateById(new ErpPurchaseApplyOrderDO().setId(orderId).setReturnCount(totalReturnCount));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePurchaseOrder(List<Long> ids) {
        // 1. 校验不处于已审批
        List<ErpPurchaseApplyOrderDO> purchaseOrders = purchaseOrderMapper.selectBatchIds(ids);
        if (CollUtil.isEmpty(purchaseOrders)) {
            return;
        }
        purchaseOrders.forEach(purchaseOrder -> {
            if (ErpAuditStatus.APPROVE.getStatus().equals(purchaseOrder.getStatus())) {
                throw exception(PURCHASE_ORDER_DELETE_FAIL_APPROVE, purchaseOrder.getNo());
            }
        });

        // 2. 遍历删除，并记录操作日志
        purchaseOrders.forEach(purchaseOrder -> {
            // 2.1 删除订单
            purchaseOrderMapper.deleteById(purchaseOrder.getId());
            // 2.2 删除订单项
            purchaseOrderItemMapper.deleteByOrderId(purchaseOrder.getId());
        });
    }

    private ErpPurchaseApplyOrderDO validatePurchaseOrderExists(Long id) {
        ErpPurchaseApplyOrderDO purchaseOrder = purchaseOrderMapper.selectById(id);
        if (purchaseOrder == null) {
            throw exception(PURCHASE_ORDER_NOT_EXISTS);
        }
        return purchaseOrder;
    }

    @Override
    public ErpPurchaseApplyOrderDO getPurchaseOrder(Long id) {
        return purchaseOrderMapper.selectById(id);
    }

    @Override
    public ErpPurchaseApplyOrderDO validatePurchaseOrder(Long id) {
        ErpPurchaseApplyOrderDO purchaseOrder = validatePurchaseOrderExists(id);
        if (ObjectUtil.notEqual(purchaseOrder.getStatus(), BpmProcessInstanceStatusEnum.APPROVE.getStatus())) {
            throw exception(PURCHASE_ORDER_NOT_APPROVE);
        }
        return purchaseOrder;
    }

    @Override
    public PageResult<ErpPurchaseApplyOrderDO> getPurchaseOrderPage(ErpPurchaseOrderPageReqVO pageReqVO) {
        return purchaseOrderMapper.selectPage(pageReqVO);
    }

    // ==================== 订单项 ====================

    @Override
    public List<ErpPurchaseApplyOrderItemDO> getPurchaseOrderItemListByOrderId(Long orderId) {
        return purchaseOrderItemMapper.selectListByOrderId(orderId);
    }

    @Override
    public List<ErpPurchaseApplyOrderItemDO> getPurchaseOrderItemListByOrderIds(Collection<Long> orderIds) {
        if (CollUtil.isEmpty(orderIds)) {
            return Collections.emptyList();
        }
        return purchaseOrderItemMapper.selectListByOrderIds(orderIds);
    }

    @Override
    public ErpPurchaseOrderExportRspVO importList(List<ErpPurchaseOrderExportVO> list) {
        ErpPurchaseOrderExportRspVO respVO = ErpPurchaseOrderExportRspVO.builder()
                .successList(new ArrayList<>())
                .failList(new ArrayList<>()).build();
        // 1.1 参数校验
        if (CollUtil.isEmpty(list)) {
            throw exception(SUPPLIER_IMPORT_EMPTY);
        }

        //查询产品物料表
        List<ErpProductVO> erpProductDOS = erpProductMapper.selectAllProductList();
        //转为map，key为name，value为对象
        Map<String, ErpProductVO> productMap = erpProductDOS.stream().collect(Collectors.toMap(ErpProductVO::getName, value -> value));



        Map<String, String> addMap = new HashMap<>();

        for (int i = 0; i < list.size(); i++) {
            ErpPurchaseOrderExportVO item = list.get(i);
            try {
                ValidationUtils.validate(BeanUtils.toBean(item, ErpPurchaseOrderExportVO.class));
            } catch (ConstraintViolationException ex) {
                respVO.getFailList().add("第"+  (i+1) + "行：" + item.getProductName() + " 导入失败：" + ex.getMessage());
                break;
            }
            //需要与物料产品表匹配校验
            if(!productMap.containsKey(item.getProductName())){
                respVO.getFailList().add("第"+  (i+1) + "行：" + item.getProductName() + " 导入失败：不存在该产品");
                break;
            }
            if(!item.getProductUnitName().equals(productMap.get(item.getProductName()).getUnit())){
                respVO.getFailList().add("第"+  (i+1) + "行：" + item.getProductName() + " 导入失败：单位不匹配,应该为"+ productMap.get(item.getProductName()).getUnit());
                break;
            }
            if(addMap.containsKey(item.getProductName())){
                respVO.getFailList().add("第"+  (i+1) + "行：" + item.getProductName() + " 导入失败：产品重复");
                break;
            }
            if(item.getCount() == null || item.getCount() <= 0){
                respVO.getFailList().add("第"+  (i+1) + "行：" + item.getProductName() + " 导入失败：数量不能小于等于0");
                break;
            }
            addMap.put(item.getProductName(), item.getProductUnitName());

            ErpPurchaseOrderExportRspVO.OrderExportItem orderExportItem = new ErpPurchaseOrderExportRspVO.OrderExportItem();
            orderExportItem.setProductId(productMap.get(item.getProductName()).getId());
            orderExportItem.setProductUnitId(productMap.get(item.getProductName()).getUnitId());
            orderExportItem.setCount(item.getCount());
            respVO.getSuccessList().add(orderExportItem);
        }

        if(!respVO.getFailList().isEmpty()){
            respVO.getSuccessList().clear();
        }
        return respVO;
    }


    @Override
    public int updateStatus(Long id, Integer status) {
        ErpPurchaseApplyOrderDO purchaseOrder = validatePurchaseOrderExists(id);
        purchaseOrder.setStatus(status);
        return purchaseOrderMapper.updateById(purchaseOrder);
    }


}
